package com.dd.keel.core.common.utils;

import java.util.Date;
import java.util.Properties;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class EmailUtil {
	
	final static private Logger LOGGER = LoggerFactory.getLogger(EmailUtil.class);
	
	public static boolean sendEMail(String mailSubject,String mailContent,String sendTo,
			String sendFrom,String smtpHost,String authUser,String authPass)
	{
		return sendEMail(mailSubject,mailContent,sendTo,null,null,sendFrom,smtpHost,authUser,authPass,false,null,-1);
	}
	
	public static boolean sendEMail(String mailSubject,String mailContent,String sendTo,
			String sendFrom,String smtpHost,String authUser,String authPass,boolean useSocksProxy,String socksProxyHost,int socksProxyPort)
	{
		return sendEMail(mailSubject,mailContent,sendTo,null,null,sendFrom,smtpHost,authUser,authPass,useSocksProxy,socksProxyHost,socksProxyPort);
	}
	
	public static boolean sendEMail(String mailSubject,String mailContent,String sendTo,String sendCc,String sendBcc,
			String sendFrom,String smtpHost,String authUser,String authPass,boolean useSocksProxy,String socksProxyHost,int socksProxyPort)
	{
		try{
			Properties props = new Properties();
			props.putAll(System.getProperties());
			if(useSocksProxy)
			{
				props.put("socksProxyHost", socksProxyHost);
				props.put("socksProxyPort", socksProxyPort+"");
			}
			props.put("mail.smtp.host", smtpHost);
			props.put("mail.smtp.auth", "true");
			Session session = Session.getInstance(props);
			session.setDebug(true);
			MimeMessage mail = new MimeMessage(session);
            mail.setFrom(new InternetAddress(sendFrom));
            mail.setSubject(mailSubject, "UTF-8");
            mail.setHeader("X-Mailer", "Task Monitor Proj");
            mail.setSentDate(new Date());
            mail.addRecipients(Message.RecipientType.TO, sendTo);
            if(sendCc!=null || sendCc.equals("") )
            {
            	mail.addRecipients(Message.RecipientType.CC, sendCc);
            }
            if(sendBcc!=null || sendBcc.equals("") )
            {
            	mail.addRecipients(Message.RecipientType.BCC, sendBcc);
            }
            mail.setText(mailContent, "UTF-8", "html");
            mail.saveChanges();
            Transport trans = session.getTransport("smtp");
            trans.connect(smtpHost, authUser, authPass);
            trans.sendMessage(mail, mail.getAllRecipients());
            trans.close();
            return true;
		}catch(Exception ex){
			LOGGER.error(ex.getMessage(), ex);
			return false;
		}
	}
	
}
